/*
 *	MemMgr.h is part of Flight_Chess_Portable
 *	Copyright (C) 2008  Poison
 *
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 *	Class:			MemMgr
 *	Description:	
 *	Author:			Poison <hbpoison@gmail.com>
 *	Date Created:	2008-02-20
 */

#pragma once

#include <vector>

using namespace std;

typedef struct _AllocRecord {
	int id;
	unsigned int size;
	void * addr;
} __attribute__((packed)) AllocRecord;

class MemMgr
{
public:
	MemMgr() { count = 0, allocated_size = 0; }
	virtual ~MemMgr();
	virtual void * alloc( unsigned int size );
	virtual int free( void * ptr );
	inline unsigned int getAllocatedSize() { return allocated_size; }
	inline unsigned int getCount() { return count; }
protected:
	void addRecord( void * addr, unsigned int size, int id );
	void delRecord( int index );
	int indexOf( void * ptr );

	unsigned int count;
	unsigned int allocated_size;
	vector<AllocRecord> records;
};

class UMemMgr: public MemMgr
{
public:
	UMemMgr();
	virtual ~UMemMgr();
	virtual void * alloc( unsigned int size );
	virtual int free( void * ptr );
	inline int getPartitionId() { return partition_id; }
protected:
	int partition_id;
};

#ifdef _KERNEL_MODE_

class KMemMgr: public UMemMgr
{
public:
	KMemMgr();
	KMemMgr( int pid );
	KMemMgr( unsigned int size, int pid, const char * heap_name );
	virtual ~KMemMgr();
	virtual void * alloc( unsigned int size );
	virtual int free( void * ptr );
	inline unsigned int getSize() { return total_size; }
protected:
	static void unlockPartition( int pid );
private:
	int heap_id;
	unsigned int total_size;
};

#endif //_KERNEL_MODE_
